package com.centaline.androidsalesblog.rx.database;

import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.events.MineInfoUpdate;
import com.centaline.androidsalesblog.model.businissobject.HistoryBo;
import com.centaline.androidsalesblog.model.databaseobject.FpHistoryDo;

import org.greenrobot.eventbus.EventBus;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Locale;

import rx.Observable;
import rx.Subscriber;

/**
 * 足迹
 * Created by guilin on 16/3/2.
 */
final class FootDeleteOnSubscribe implements Observable.OnSubscribe<Boolean> {

    private final ArrayList<HistoryBo> arrayList;

    public FootDeleteOnSubscribe(ArrayList<HistoryBo> arrayList) {
        this.arrayList = arrayList;
    }

    @Override
    public void call(Subscriber<? super Boolean> subscriber) {
        if (arrayList.size() > 0) {
            final StringBuilder sql = new StringBuilder();
            sql.append("(");
            for (HistoryBo historyBo : arrayList) {
                sql.append("'")
                        .append(historyBo.getResourceId())
                        .append("'")
                        .append(",");
            }
            sql.deleteCharAt(sql.length() - 1);
            sql.append(")");
            DataSupport.deleteAll(FpHistoryDo.class,
                    String.format(Locale.CHINA, "cityCode = ? and resourceId in %s", sql.toString())
                    , AppConstant.CityCode);
            EventBus.getDefault().post(new MineInfoUpdate(0));
            if (!subscriber.isUnsubscribed()) {
                subscriber.onNext(true);
            }
        } else {
            if (!subscriber.isUnsubscribed()) {
                subscriber.onNext(false);
            }
        }
        subscriber.onCompleted();
    }

}
